package com.hrm.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.hrm.mapper.NoticeMapper;
import com.hrm.pojo.DTO.NoticePageDTO;
import com.hrm.pojo.Notice;
import com.hrm.service.NoticeService;
import com.hrm.utils.JwtUtil;
import com.hrm.utils.entity.PageResult;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@Service
public class NoticeServiceImpl implements NoticeService {
    @Autowired
    private NoticeMapper noticeMapper;
    @Autowired
    private JwtUtil jwtUtil;
    @Autowired
    private HttpServletRequest request;
    /**
     * 分页查询
     * @param noticePageDTO
     * @return
     * @throws Exception
     */
    @Override
    public PageResult<Notice> pageResult(NoticePageDTO noticePageDTO) throws Exception {
        Page<Notice> pageNotice=PageHelper.startPage(noticePageDTO.getPage(),5);
        List<Notice> list=noticeMapper.selectByTitleAndContext(noticePageDTO.getTitle(), noticePageDTO.getContent());
        return new PageResult<>(pageNotice.getTotal(),list);
    }

    /**
     * 修改公告
     * @param notice
     * @return
     * @throws Exception
     */
    @Override
    public boolean updateByTitle(Notice notice) throws Exception {
        //通过token获取用户id
        String token = request.getHeader("Authorization");
        Claims claims = jwtUtil.parseJWT(token);
        String userId = claims.getId();
        //返回增加数据是否成功
        notice.setUserId(Integer.valueOf(userId));
        return noticeMapper.updateByPrimaryKeySelective(notice)>0;
    }

    /**
     * 删除公告
     * @param id
     * @return
     * @throws Exception
     */
    @Override
    public boolean deleteById(Integer id) throws Exception {
        return noticeMapper.deleteByPrimaryKey(id)>0;
    }

    /**
     * 增加公告
     * @param notice
     * @return
     * @throws Exception
     */
    @Override
    public boolean add(Notice notice) throws Exception {
        //通过token获取用户id
        String token = request.getHeader("Authorization");
        Claims claims = jwtUtil.parseJWT(token);
        String userId = claims.getId();
        //返回增加数据是否成功
        notice.setUserId(Integer.valueOf(userId));
        return noticeMapper.insertSelective(notice)>0;
    }
}
